import { useState, useEffect } from 'react'
import  {Producer,  Observer} from './1.4'
import {} from './1.4rx'

interface userItem {
  id: number;
  name: string;
  type: string;
}

const userData: userItem[] = [
  { id: 1, name: "Martin", type: "Manager" },
  { id: 2, name: "Alex", type: "developer" },
  { id: 3, name: "Bob", type: "client" },
];


const getMockUserData = (id:number) => {
  return new Promise((resolve, reject) => {
    let user = userData.find((u) => u.id === id)
    if (user) {
        // 模拟接口请求
        setTimeout(() => resolve(user), Math.random() * 3000);
    } else {
        setTimeout(() => reject('user not found'), Math.random() * 3000);
    }
  });
};

let subject = new Producer()

const User = () => {
  const [user, setUser] = useState(1);
  const [data, setData] = useState< userItem >();
  const [loading, setLoading] = useState(false);

  const handleClick = () => {

    subject.addListener(new Observer('地球'))
    subject.addListener(new Observer('月亮'))

    setTimeout(() => {
      subject.notify('💥')
    }, 3000)
  }

  useEffect(() => {
    let canceled = true;
    setLoading(true);
    getMockUserData(user).then(
      (data) => {
        if (canceled) {
          setData(data as userItem);
          setLoading(false);
        }
        
      },
      (error) => {
        console.log(error);
      }
    );
    return () => {canceled = false}
  }, [user]);

  return (
    <>
      <button onClick={() => setUser(1)}>Bob</button>
      <button onClick={() => setUser(2)}>Alex</button>
      <button onClick={() => setUser(3)}>Martin</button>
      <button onClick={handleClick}>subject</button>
      <div>{`Active User id ${user}`}</div>
      <div>{loading ? "Loading...." : JSON.stringify(data, null, 4)}</div>
    </>
  )
}

export default User